/*
 * Copyright 2020-2023 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.security.oauth2.server.authorization.web;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.core.log.LogMessage;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeRequestAuthenticationException;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeRequestAuthenticationProvider;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeRequestAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationConsentAuthenticationProvider;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationConsentAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.web.authentication.DelegatingAuthenticationConverter;
import org.springframework.security.oauth2.server.authorization.web.authentication.OAuth2AuthorizationCodeRequestAuthenticationConverter;
import org.springframework.security.oauth2.server.authorization.web.authentication.OAuth2AuthorizationConsentAuthenticationConverter;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.security.web.util.RedirectUrlBuilder;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.security.web.util.matcher.AndRequestMatcher;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.NegatedRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.util.UriUtils;

/**
 * A {@code Filter} for the OAuth 2.0 Authorization Code Grant,
 * which handles the processing of the OAuth 2.0 Authorization Request and Consent.
 * 授权端点，即RP(客户端)跳转到OP(授权端)的认证入口，且EU(认证个体信息)认证通过后，OP重定向回RP，且附加code参数
 * @author Joe Grandja
 * @author Paurav Munshi
 * @author Daniel Garnier-Moiroux
 * @author Anoop Garlapati
 * @author Dmitriy Dubson
 * @since 0.0.1
 * @see AuthenticationManager
 * @see OAuth2AuthorizationCodeRequestAuthenticationProvider
 * @see OAuth2AuthorizationConsentAuthenticationProvider
 * @see <a target="_blank" href="https://datatracker.ietf.org/doc/html/rfc6749#section-4.1">Section 4.1 Authorization Code Grant</a>
 * @see <a target="_blank" href="https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.1">Section 4.1.1 Authorization Request</a>
 * @see <a target="_blank" href="https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2">Section 4.1.2 Authorization Response</a>
 */
public final class OAuth2AuthorizationEndpointFilter extends OncePerRequestFilter {
	/**
	 * The default endpoint {@code URI} for authorization requests.
	 */
	private static final String DEFAULT_AUTHORIZATION_ENDPOINT_URI = "/oauth2/authorize";

	private final AuthenticationManager authenticationManager;
	private final RequestMatcher authorizationEndpointMatcher;
	private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
	private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();
	//默认DelegatingAuthenticationConverter
	private AuthenticationConverter authenticationConverter;
	private AuthenticationSuccessHandler authenticationSuccessHandler = this::sendAuthorizationResponse;
	private AuthenticationFailureHandler authenticationFailureHandler = this::sendErrorResponse;
	private SessionAuthenticationStrategy sessionAuthenticationStrategy = (authentication, request, response) -> {};
	//授权页面
	private String consentPage;

	/**
	 * Constructs an {@code OAuth2AuthorizationEndpointFilter} using the provided parameters.
	 *
	 * @param authenticationManager the authentication manager
	 */
	public OAuth2AuthorizationEndpointFilter(AuthenticationManager authenticationManager) {
		this(authenticationManager, DEFAULT_AUTHORIZATION_ENDPOINT_URI);
	}

	/**
	 * Constructs an {@code OAuth2AuthorizationEndpointFilter} using the provided parameters.
	 *
	 * @param authenticationManager the authentication manager 默认providerManager
	 * @param authorizationEndpointUri the endpoint {@code URI} for authorization requests  默认/oauth2/authorize
	 */
	public OAuth2AuthorizationEndpointFilter(AuthenticationManager authenticationManager, String authorizationEndpointUri) {
		Assert.notNull(authenticationManager, "authenticationManager cannot be null");
		Assert.hasText(authorizationEndpointUri, "authorizationEndpointUri cannot be empty");
		this.authenticationManager = authenticationManager;
		//初始化当前过滤器的路径匹配器
		this.authorizationEndpointMatcher = createDefaultRequestMatcher(authorizationEndpointUri);
		//这次默认帮我们创建了DelegatingAuthenticationConverter，但是再configure中会被重新赋值
		this.authenticationConverter = new DelegatingAuthenticationConverter(
				Arrays.asList(
						new OAuth2AuthorizationCodeRequestAuthenticationConverter(),
						new OAuth2AuthorizationConsentAuthenticationConverter()));
	}
    //AntPathRequestMatcher:定义一个请求匹配器  OrRequestMatcher、AndRequestMatcher:组合多个路径匹配器  NegatedRequestMatcher：是匹配器进行取反
	private static RequestMatcher createDefaultRequestMatcher(String authorizationEndpointUri) {
		// /oauth2/authorize get 请求
		RequestMatcher authorizationRequestGetMatcher = new AntPathRequestMatcher(
				authorizationEndpointUri, HttpMethod.GET.name());
		// /oauth2/authorize post 请求
		RequestMatcher authorizationRequestPostMatcher = new AntPathRequestMatcher(
				authorizationEndpointUri, HttpMethod.POST.name());
		// 存在scope参数并且包含openId
		RequestMatcher openidScopeMatcher = request -> {
			String scope = request.getParameter(OAuth2ParameterNames.SCOPE);
			return StringUtils.hasText(scope) && scope.contains(OidcScopes.OPENID);
		};
		// 请求参数中必须包含response_type(模式)
		RequestMatcher responseTypeParameterMatcher = request ->
				request.getParameter(OAuth2ParameterNames.RESPONSE_TYPE) != null;
        // (get请求{普通授权请求}) 或者 (post请求且含有response_type，scope参数，且scope参数必须包含openId{oidc认证请求}) -- client授权请求
		RequestMatcher authorizationRequestMatcher = new OrRequestMatcher(
				authorizationRequestGetMatcher,
				new AndRequestMatcher(
						authorizationRequestPostMatcher, responseTypeParameterMatcher, openidScopeMatcher));
		// post请求且没有response_type参数{授权登录请求样式匹配}
		RequestMatcher authorizationConsentMatcher = new AndRequestMatcher(
				authorizationRequestPostMatcher, new NegatedRequestMatcher(responseTypeParameterMatcher));
        //二者满足其一即可 不过需要注意其里面的路径信息默认均为/oauth2/authorize
		return new OrRequestMatcher(authorizationRequestMatcher, authorizationConsentMatcher);
	}
    //流程：(1)客户端发起授权请求(/oauth2/authorize)
	// ->(2)授权服务器接收到该请求后由该过滤器进行处理->(3)客户端发起的请求为get请求，最终由OAuth2AuthorizationCodeRequestAuthenticationConverter
	// 进行转化生成OAuth2AuthorizationCodeRequestAuthenticationToken对象，进而使用OAuth2AuthorizationCodeRequestAuthenticationProvider处理判断是否登录认证
	// ->(4)未认证跳转到登录页面，登录完成重新转发缓存的授权请求->(5)此时该过滤器又会接到一个跟客户端发起的一模一样的授权请求A
	// ->(6)还是由OAuth2AuthorizationCodeRequestAuthenticationProvider处理，此时再处理A请求时获取的登录信息就已经认证了,
	// 其会继续判断是否需要授权->(7)如果需要授权其会返回一个OAuth2AuthorizationConsentAuthenticationToken对象，根据该对象类型重定向到授权页面->
	//(8)再授权页面点击授权按钮后会重新发起一个请求，其样式和授权请求一样，但是其是post且不包含response_type
	// ->(9)此时会由OAuth2AuthorizationConsentAuthenticationConverter进行处理返回一个OAuth2AuthorizationConsentAuthenticationToken
	// 对象进而由OAuth2AuthorizationConsentAuthenticationProvider进行处理
	// 上面的流程是一个包含登录和授权的比较全的流程，但是需要注意再实际应用中，登录和授权非必须  如果已经在该过程之前登陆过那么就需要剔除登录流程，如果不需要授权，授权流程也需要剔除
	// 如果不需要授权OAuth2AuthorizationConsentAuthenticationConverter OAuth2AuthorizationConsentAuthenticationProvider就无任何作用
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		// 首先根据路径匹配是否要开始授权，如 默认/oauth2/authorize
		if (!this.authorizationEndpointMatcher.matches(request)) {
			filterChain.doFilter(request, response);
			return;
		}

		try {
			// 对request请求中的参数进行校验并最终封装为OAuth2AuthorizationCodeRequestAuthenticationToken{未认证}对象(OAuth2AuthorizationCodeRequestAuthenticationConverter)
			// 或者OAuth2AuthorizationConsentAuthenticationToken{已认证}对象
			// (OAuth2AuthorizationConsentAuthenticationConverter post请求且请求参数中不包含response_type 授权页面点击授权按钮时发起的请求)
			Authentication authentication = this.authenticationConverter.convert(request);
			// 当返回的对象为OAuth2AuthorizationConsentAuthenticationToken或者OAuth2AuthorizationCodeRequestAuthenticationToken对象时均符合
			if (authentication instanceof AbstractAuthenticationToken) {
				((AbstractAuthenticationToken) authentication)
						//返回WebAuthenticationDetails对象，包含请求ip和sessionId信息
						.setDetails(this.authenticationDetailsSource.buildDetails(request));
			}
			// 具体调用OAuth2AuthorizationCodeRequestAuthenticationProvider其中会判断是否登录和授权，分别返回不同类型的Authentication实现类，后续会根据类型进行判断是否授权
			// OAuth2AuthorizationConsentAuthenticationProvider 主要用来处理授权页面点击授权按钮发送来的请求生成授权码
			// 需要注意的是两个provider最终返回的对象均为OAuth2AuthorizationCodeRequestAuthenticationToken(OAuth2AuthorizationCode属性含有code)
			Authentication authenticationResult = this.authenticationManager.authenticate(authentication);
			// 授权服务器还未登录，直接让后面的处理，会抛出异常由ExceptionTranslationFilter处理，最后由LoginUrlAuthenticationEntryPoint重定向至登录页面如/login
			// 注意，ExceptionTranslationFilter处理时会先将原始请求(授权请求/oauth2/authorize)存储到session中，以便登录后进行重定向，但是登录不会走授权的filterChain，而是websecurity中登录执行链。
			// 登陆成功后 由UsernamePasswordAuthenticationFilter的AuthenticationSuccessHandler处理，其实现类SavedRequestAwareAuthenticationSuccessHandler处理，
			// 该handler在session中拿取之前暂存的请求信息，再次重定向到 默认的开始授权路径/oauth2/authorize（注意，不是redirect_uri）
			if (!authenticationResult.isAuthenticated()) {
				// If the Principal (Resource Owner) is not authenticated then
				// pass through the chain with the expectation that the authentication process
				// will commence via AuthenticationEntryPoint
				filterChain.doFilter(request, response);
				return;
			}
			// 由上面的重定向，用户已经登录（登录信息也是通过session传递的）
			// 如果还没授权，该类型就为OAuth2AuthorizationConsentAuthenticationToken，如果授权过了，这里就不是了
			// 具体流程在OAuth2AuthorizationCodeRequestAuthenticationProvider中
			if (authenticationResult instanceof OAuth2AuthorizationConsentAuthenticationToken) {
				if (this.logger.isTraceEnabled()) {
					this.logger.trace("Authorization consent is required");
				}
				// 发送重定向到授权页面  authentication为最原始的授权请求参数信息
				// authenticationResult为根据authentication生成的需要授权数据信息，里面的state是从新生成的
				sendAuthorizationConsent(request, response,
						(OAuth2AuthorizationCodeRequestAuthenticationToken) authentication,
						(OAuth2AuthorizationConsentAuthenticationToken) authenticationResult);
				return;
			}
			//会话注册处理，再OAuth2AuthorizationServerConfigurer进行的设置
			this.sessionAuthenticationStrategy.onAuthentication(
					authenticationResult, request, response);
			// 如果都授权，开始执行code返回流程，该handler是匿名类，执行本类#sendAuthorizationResponse
			// 用户同意授权后{再授权页面点击授权按钮}由OAuth2AuthorizationConsentAuthenticationProvider处理在该Provider中会生成code
			// 如果已经默认授权不需要授权页面则由OAuth2AuthorizationCodeRequestAuthenticationProvider处理生成code
			this.authenticationSuccessHandler.onAuthenticationSuccess(
					request, response, authenticationResult);

		} catch (OAuth2AuthenticationException ex) {
			if (this.logger.isTraceEnabled()) {
				this.logger.trace(LogMessage.format("Authorization request failed: %s", ex.getError()), ex);
			}
			// 授权失败异常处理
			this.authenticationFailureHandler.onAuthenticationFailure(request, response, ex);
		}
	}

	/**
	 * Sets the {@link AuthenticationDetailsSource} used for building an authentication details instance from {@link HttpServletRequest}.
	 *
	 * @param authenticationDetailsSource the {@link AuthenticationDetailsSource} used for building an authentication details instance from {@link HttpServletRequest}
	 * @since 0.3.1
	 */
	public void setAuthenticationDetailsSource(AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) {
		Assert.notNull(authenticationDetailsSource, "authenticationDetailsSource cannot be null");
		this.authenticationDetailsSource = authenticationDetailsSource;
	}

	/**
	 * Sets the {@link AuthenticationConverter} used when attempting to extract an Authorization Request (or Consent) from {@link HttpServletRequest}
	 * to an instance of {@link OAuth2AuthorizationCodeRequestAuthenticationToken} or {@link OAuth2AuthorizationConsentAuthenticationToken}
	 * used for authenticating the request.
	 *
	 * @param authenticationConverter the {@link AuthenticationConverter} used when attempting to extract an Authorization Request (or Consent) from {@link HttpServletRequest}
	 */
	public void setAuthenticationConverter(AuthenticationConverter authenticationConverter) {
		Assert.notNull(authenticationConverter, "authenticationConverter cannot be null");
		this.authenticationConverter = authenticationConverter;
	}

	/**
	 * Sets the {@link AuthenticationSuccessHandler} used for handling an {@link OAuth2AuthorizationCodeRequestAuthenticationToken}
	 * and returning the {@link OAuth2AuthorizationResponse Authorization Response}.
	 *
	 * @param authenticationSuccessHandler the {@link AuthenticationSuccessHandler} used for handling an {@link OAuth2AuthorizationCodeRequestAuthenticationToken}
	 */
	public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler authenticationSuccessHandler) {
		Assert.notNull(authenticationSuccessHandler, "authenticationSuccessHandler cannot be null");
		this.authenticationSuccessHandler = authenticationSuccessHandler;
	}

	/**
	 * Sets the {@link AuthenticationFailureHandler} used for handling an {@link OAuth2AuthorizationCodeRequestAuthenticationException}
	 * and returning the {@link OAuth2Error Error Response}.
	 *
	 * @param authenticationFailureHandler the {@link AuthenticationFailureHandler} used for handling an {@link OAuth2AuthorizationCodeRequestAuthenticationException}
	 */
	public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
		Assert.notNull(authenticationFailureHandler, "authenticationFailureHandler cannot be null");
		this.authenticationFailureHandler = authenticationFailureHandler;
	}

	/**
	 * Sets the {@link SessionAuthenticationStrategy} used for handling an {@link OAuth2AuthorizationCodeRequestAuthenticationToken}
	 * before calling the {@link AuthenticationSuccessHandler}.
	 * If OpenID Connect is enabled, the default implementation tracks OpenID Connect sessions using a {@link SessionRegistry}.
	 *
	 * @param sessionAuthenticationStrategy the {@link SessionAuthenticationStrategy} used for handling an {@link OAuth2AuthorizationCodeRequestAuthenticationToken}
	 * @since 1.1
	 */
	public void setSessionAuthenticationStrategy(SessionAuthenticationStrategy sessionAuthenticationStrategy) {
		Assert.notNull(sessionAuthenticationStrategy, "sessionAuthenticationStrategy cannot be null");
		this.sessionAuthenticationStrategy = sessionAuthenticationStrategy;
	}

	/**
	 * Specify the URI to redirect Resource Owners to if consent is required. A default consent
	 * page will be generated when this attribute is not specified.
	 *
	 * @param consentPage the URI of the custom consent page to redirect to if consent is required (e.g. "/oauth2/consent")
	 */
	public void setConsentPage(String consentPage) {
		this.consentPage = consentPage;
	}

	private void sendAuthorizationConsent(HttpServletRequest request, HttpServletResponse response,
			OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication,
			OAuth2AuthorizationConsentAuthenticationToken authorizationConsentAuthentication) throws IOException {
		// 获取客户id
		String clientId = authorizationConsentAuthentication.getClientId();
		// 获取认证信息
		Authentication principal = (Authentication) authorizationConsentAuthentication.getPrincipal();
		// 获取请求要求的scope范围，该范围会再授权页进行展示勾选(openId会自动剔除无需展示)  请求read,write 我们可以仅勾选read，这样该请求只有read权限
		Set<String> requestedScopes = authorizationCodeRequestAuthentication.getScopes();
		// 获取已经给该用户授权了哪些范围
		Set<String> authorizedScopes = authorizationConsentAuthentication.getScopes();
		// 获取授权请求对应的新生成的state,防止csrf
		String state = authorizationConsentAuthentication.getState();
		// 是否设置了授权页面，默认为null
		if (hasConsentUri()) {
			String redirectUri = UriComponentsBuilder.fromUriString(resolveConsentUri(request))
					.queryParam(OAuth2ParameterNames.SCOPE, String.join(" ", requestedScopes))
					.queryParam(OAuth2ParameterNames.CLIENT_ID, clientId)
					.queryParam(OAuth2ParameterNames.STATE, state)
					.toUriString();
			this.redirectStrategy.sendRedirect(request, response, redirectUri);
		} else {
			if (this.logger.isTraceEnabled()) {
				this.logger.trace("Displaying generated consent screen");
			}
			//帮我们通过代码的方式生成授权页面进行授权
			DefaultConsentPage.displayConsent(request, response, clientId, principal, requestedScopes, authorizedScopes, state, Collections.emptyMap());
		}
	}

	private boolean hasConsentUri() {
		return StringUtils.hasText(this.consentPage);
	}

	private String resolveConsentUri(HttpServletRequest request) {
		if (UrlUtils.isAbsoluteUrl(this.consentPage)) {
			return this.consentPage;
		}
		RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();
		urlBuilder.setScheme(request.getScheme());
		urlBuilder.setServerName(request.getServerName());
		urlBuilder.setPort(request.getServerPort());
		urlBuilder.setContextPath(request.getContextPath());
		urlBuilder.setPathInfo(this.consentPage);
		return urlBuilder.getUrl();
	}

	private void sendAuthorizationResponse(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException {

		OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication =
				(OAuth2AuthorizationCodeRequestAuthenticationToken) authentication;
		// 将生成code和RedirectUri进行拼接处理
		UriComponentsBuilder uriBuilder = UriComponentsBuilder
				.fromUriString(authorizationCodeRequestAuthentication.getRedirectUri())
				.queryParam(OAuth2ParameterNames.CODE, authorizationCodeRequestAuthentication.getAuthorizationCode().getTokenValue());
		// 返回接受的state，防止CSRF
		if (StringUtils.hasText(authorizationCodeRequestAuthentication.getState())) {
			uriBuilder.queryParam(
					OAuth2ParameterNames.STATE,
					UriUtils.encode(authorizationCodeRequestAuthentication.getState(), StandardCharsets.UTF_8));
		}
		String redirectUri = uriBuilder.build(true).toUriString();		// build(true) -> Components are explicitly encoded
		// 带着code和state参数重定向到用户给的redirect_uri
		this.redirectStrategy.sendRedirect(request, response, redirectUri);
	}
    //将异常信息返回给客户端
	private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException {

		OAuth2AuthorizationCodeRequestAuthenticationException authorizationCodeRequestAuthenticationException =
				(OAuth2AuthorizationCodeRequestAuthenticationException) exception;
		OAuth2Error error = authorizationCodeRequestAuthenticationException.getError();
		OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication =
				authorizationCodeRequestAuthenticationException.getAuthorizationCodeRequestAuthentication();

		if (authorizationCodeRequestAuthentication == null ||
				!StringUtils.hasText(authorizationCodeRequestAuthentication.getRedirectUri())) {
			response.sendError(HttpStatus.BAD_REQUEST.value(), error.toString());
			return;
		}

		if (this.logger.isTraceEnabled()) {
			this.logger.trace("Redirecting to client with error");
		}

		UriComponentsBuilder uriBuilder = UriComponentsBuilder
				.fromUriString(authorizationCodeRequestAuthentication.getRedirectUri())
				.queryParam(OAuth2ParameterNames.ERROR, error.getErrorCode());
		if (StringUtils.hasText(error.getDescription())) {
			uriBuilder.queryParam(
					OAuth2ParameterNames.ERROR_DESCRIPTION,
					UriUtils.encode(error.getDescription(), StandardCharsets.UTF_8));
		}
		if (StringUtils.hasText(error.getUri())) {
			uriBuilder.queryParam(
					OAuth2ParameterNames.ERROR_URI,
					UriUtils.encode(error.getUri(), StandardCharsets.UTF_8));
		}
		if (StringUtils.hasText(authorizationCodeRequestAuthentication.getState())) {
			uriBuilder.queryParam(
					OAuth2ParameterNames.STATE,
					UriUtils.encode(authorizationCodeRequestAuthentication.getState(), StandardCharsets.UTF_8));
		}
		String redirectUri = uriBuilder.build(true).toUriString();		// build(true) -> Components are explicitly encoded
		this.redirectStrategy.sendRedirect(request, response, redirectUri);
	}

}
